<?php
/**
 * To C参与活动用户控制器
 */
namespace Beerus\Modules\DesignerCompetition2021\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Article;
use Doraemon\model\DesignerCompetition2021\toc\ToCPrize;
use Doraemon\model\DesignerCompetition2021\toc\ToCUserInfo;
use Doraemon\service\DesignerCompetition2021\ToC;
use Doraemon\service\Member;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Doraemon\cache\DesignerCompetition2021\DcToC as cDcToC;

class ToCUserController extends Controller {
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content) {
        $page = $request->get('page', 1);
        $pageSize = $request->get('per_page', self::PAGE_SIZE);
        $condition = [];
        $request = $request->all();
        if ($request['uid']) {
            $condition['uid'] = $request['uid'];
        }
        if ($request['nick']) {
            $uid = \Doraemon\model\Member::getUidByNick($request['nick']);
            $condition['uid'] = $uid ?? '';
        }
        if ($request['is_prize']) {
            if ($request['is_prize'] == 1) {
                $condition['prize_ids[!]'] = '';
            } else {
                $condition['prize_ids'] = '';
            }
        }
        if ($request['is_forecast']) {
            if ($request['is_forecast'] == 1) {
                $condition['forecast_aids[!]'] = '';
            } else {
                $condition['forecast_aids'] = '';
            }
        }
        $total = ToCUserInfo::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = ToCUserInfo::select('*', $condition);
        $prizeList = ToCPrize::getAllPrizeList();
        $prizeOption = array_combine(array_column($prizeList, 'id'),array_column($prizeList, 'name'));
        $this->formatList($list);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $prizeOption) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function (Grid\Filter $filter) use ($prizeOption) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
                    $filter->column(1 / 2, function ($filter) use ($prizeOption) {
                        $filter->equal('is_prize', '是否中奖')->select([1=>'是', 2=>'否']);
                        $filter->equal('is_forecast', '是否预测')->select([1=>'是', 2=>'否']);
                    });
                    $filter->expand();
                });

                $grid->column('id', 'ID');
                $grid->column('uid', 'UID')->width(150);
                $grid->column('nick', '昵称')->width(250);
                $grid->column('prize_ids', '已获得奖项')->display(function () {
                    if ($this->prize_title_list) {
                        return implode(',', $this->prize_title_list);
                    }
                    return '未中奖';
                })->width(400);
                $grid->column('forecast_article_titles', '已预测整屋')->display(function() {
                    if ($this->forecast_article_titles) {
                        return implode('<br>', $this->forecast_article_titles);
                    }
                    return '未预测';
                })->width(500);
                $grid->column('play_num', '抽奖次数');
                $grid->column('support_num', '助力值');
                $grid->column('is_vip', '是否是vip')->display(function() {
                    return $this->is_vip == ToCUserInfo::VIP_YES ? '是' : '否';
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
//                    if ($this->row->is_vip == ToCUserInfo::VIP_NO) {
//                        $actions->disableDelete();
//                    }
//                    $actions->disableEdit();
                });
            }
        );
        return $content
            ->header('TOC活动参与人员管理')
            ->row($gridList);
    }

    public function edit(Request $request, Content $content, $id = 0) {
        if ($id) {
            $data = ToCUserInfo::get('*', ['id' => $id]);
            $form = new Form($data);
        } else {
            $form = new Form([]);
        }
        if (!empty($id)) {
            $form->text('id', 'ID')->readOnly();
            $form->text('uid', 'UID')->readOnly();
        } else {
            $form->text('uid', 'UID')->required();
        }
        $form->text('play_num', '抽奖次数')->required();
        $form->select('is_vip', '是否是vip')
            ->options([
                ToCUserInfo::VIP_YES => 'vip用户',
                ToCUserInfo::VIP_NO => '非vip用户'
            ])
            ->default(ToC::PRIZE_TYPE_LOSE)
            ->required();
        $form->confirm('确定提交吗？');
        $form->action('/admin/DesignerCompetition2021/toc/user/save');

        $header = '信息修改';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => '用户列表'],
                ['text' => '编辑用户信息'],
            )->row($tab);
    }

    // 编辑奖项
    public function save(Request $request) {
        $request = $request->all();
        if (!Member::getUserInfoByUid($request['uid'])) {
            $error = new MessageBag(['title' => '该用户不存在']);
            return back()->with(compact('error'));
        }
        $data = [
            'uid' => $request['uid'],
            'play_num' => $request['play_num'],
            'is_vip' => $request['is_vip'],
        ];
        if (isset($request['id'])) {
            $rs = ToCUserInfo::updateInfo($data, ['id' => $request['id']]);
        } else {
            if (ToCUserInfo::get('*', ['uid' => $request['uid']])) {
                $error = new MessageBag(['title' => '已经存在该用户']);
                return back()->with(compact('error'));
            }
            $rs = ToCUserInfo::addInfo($data);
        }
        if ($rs === false) {
            $error = new MessageBag(['title' => '操作失败']);
            return back()->with(compact('error'));
        }
        cDcToC::setUserPlayNum($request['uid'], $request['play_num']);
        $success = new MessageBag(['title' => '操作成功']);
        return redirect('/admin/DesignerCompetition2021/toc/user')->with(compact('success'));
    }

    // 删除用户
    public function del($id) {
        $user = ToCUserInfo::get('*', ['id' => $id]);
        if ($user) {
            if (ToCUserInfo::delete(['id' => $id]) === false) {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
            cDcToC::removeUserPlayNum($user['uid']);
            cDcToC::removeTodayShareTime($user['uid']);
            cDcToC::removeTodaySupportTime($user['uid']);
            cDcToC::removeUserCurPrizePool($user['uid']);
            $userList = ToCUserInfo::select('*');
            foreach ($userList as $userItem) {
                cDcToC::removeTodaySupportRelation($user['uid'], $userItem['uid']);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "该评审不存在",
            ]);
        }
    }

    public function saveSkuNum(Request $request, $id) {
        $remark = $request->input('value');
        if (!ToCPrize::updateInfo(['sku_num' => $remark], ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json([
            'status' => true,
        ]);
    }

    public function formatList(&$list) {
        foreach ($list as &$item) {
            $item['nick'] = \Doraemon\model\Member::getNickByUid($item['uid']);
            // 处理整屋名称
            $articleTitleList = [];
            if ($item['forecast_aids']) {
                $forecastAids = explode(',', $item['forecast_aids']);
                $articleList = Article::getAllArticles($forecastAids);
                $articleTitleList = array_column($articleList, 'title');
            }
            $item['forecast_article_titles'] = $articleTitleList;
            $prizeTitleList = [];
            if ($item['prize_ids']) {
                $prizeids = explode(',', $item['prize_ids']);
                $prizeList = ToCPrize::getPrizeInfoListByIds($prizeids);
                $prizeTitleList = array_column($prizeList, 'name');
            }
            $item['prize_title_list'] = $prizeTitleList;
        }
    }
}
